#!/bin/bash

# LifeVerse监控系统启动脚本

set -e

echo "🚀 启动LifeVerse监控系统..."

# 检查Docker是否运行
if ! docker info > /dev/null 2>&1; then
    echo "❌ Docker未运行，请先启动Docker"
    exit 1
fi

# 检查Docker Compose是否安装
if ! command -v docker-compose &> /dev/null; then
    echo "❌ Docker Compose未安装，请先安装Docker Compose"
    exit 1
fi

# 创建监控配置目录
echo "📁 创建监控配置目录..."
mkdir -p monitoring/prometheus/rules
mkdir -p monitoring/grafana/provisioning/datasources
mkdir -p monitoring/grafana/provisioning/dashboards
mkdir -p monitoring/grafana/dashboards
mkdir -p monitoring/alertmanager
mkdir -p monitoring/loki
mkdir -p monitoring/promtail

# 检查配置文件是否存在
if [ ! -f "monitoring/prometheus/prometheus.yml" ]; then
    echo "❌ Prometheus配置文件不存在: monitoring/prometheus/prometheus.yml"
    exit 1
fi

if [ ! -f "monitoring/alertmanager/alertmanager.yml" ]; then
    echo "❌ AlertManager配置文件不存在: monitoring/alertmanager/alertmanager.yml"
    exit 1
fi

# 创建Grafana数据源配置
cat > monitoring/grafana/provisioning/datasources/prometheus.yml << EOF
apiVersion: 1

datasources:
  - name: Prometheus
    type: prometheus
    access: proxy
    url: http://prometheus:9090
    isDefault: true
    editable: true

  - name: Loki
    type: loki
    access: proxy
    url: http://loki:3100
    editable: true
EOF

# 创建Grafana仪表盘配置
cat > monitoring/grafana/provisioning/dashboards/dashboard.yml << EOF
apiVersion: 1

providers:
  - name: 'default'
    orgId: 1
    folder: ''
    type: file
    disableDeletion: false
    updateIntervalSeconds: 10
    allowUiUpdates: true
    options:
      path: /var/lib/grafana/dashboards
EOF

# 创建Loki配置
cat > monitoring/loki/loki-config.yml << EOF
auth_enabled: false

server:
  http_listen_port: 3100
  grpc_listen_port: 9096

common:
  path_prefix: /loki
  storage:
    filesystem:
      chunks_directory: /loki/chunks
      rules_directory: /loki/rules
  replication_factor: 1
  ring:
    instance_addr: 127.0.0.1
    kvstore:
      store: inmemory

query_range:
  results_cache:
    cache:
      embedded_cache:
        enabled: true
        max_size_mb: 100

schema_config:
  configs:
    - from: 2020-10-24
      store: boltdb-shipper
      object_store: filesystem
      schema: v11
      index:
        prefix: index_
        period: 24h

ruler:
  alertmanager_url: http://localhost:9093

limits_config:
  reject_old_samples: true
  reject_old_samples_max_age: 168h

chunk_store_config:
  max_look_back_period: 0s

table_manager:
  retention_deletes_enabled: false
  retention_period: 0s

compactor:
  working_directory: /loki/boltdb-shipper-compactor
  shared_store: filesystem
EOF

# 创建Promtail配置
cat > monitoring/promtail/promtail-config.yml << EOF
server:
  http_listen_port: 9080
  grpc_listen_port: 0

positions:
  filename: /tmp/positions.yaml

clients:
  - url: http://loki:3100/loki/api/v1/push

scrape_configs:
  - job_name: system
    static_configs:
      - targets:
          - localhost
        labels:
          job: varlogs
          __path__: /var/log/*log

  - job_name: containers
    static_configs:
      - targets:
          - localhost
        labels:
          job: containerlogs
          __path__: /var/lib/docker/containers/*/*log
    pipeline_stages:
      - json:
          expressions:
            output: log
            stream: stream
            attrs:
      - json:
          expressions:
            tag:
          source: attrs
      - regex:
          expression: (?P<container_name>(?:[^|]*))\|
          source: tag
      - timestamp:
          format: RFC3339Nano
          source: time
      - labels:
          stream:
          container_name:
      - output:
          source: output
EOF

# 创建基础的Grafana仪表盘
cat > monitoring/grafana/dashboards/lifeverse-overview.json << 'EOF'
{
  "dashboard": {
    "id": null,
    "title": "LifeVerse系统概览",
    "tags": ["lifeverse"],
    "style": "dark",
    "timezone": "browser",
    "panels": [
      {
        "id": 1,
        "title": "系统健康状态",
        "type": "stat",
        "targets": [
          {
            "expr": "up{job=\"lifeverse-platform\"}",
            "legendFormat": "系统状态"
          }
        ],
        "fieldConfig": {
          "defaults": {
            "color": {
              "mode": "thresholds"
            },
            "thresholds": {
              "steps": [
                {"color": "red", "value": 0},
                {"color": "green", "value": 1}
              ]
            }
          }
        },
        "gridPos": {"h": 8, "w": 6, "x": 0, "y": 0}
      },
      {
        "id": 2,
        "title": "JVM内存使用率",
        "type": "stat",
        "targets": [
          {
            "expr": "lifeverse_jvm_memory_usage_percent",
            "legendFormat": "内存使用率"
          }
        ],
        "fieldConfig": {
          "defaults": {
            "unit": "percent",
            "color": {
              "mode": "thresholds"
            },
            "thresholds": {
              "steps": [
                {"color": "green", "value": 0},
                {"color": "yellow", "value": 70},
                {"color": "red", "value": 85}
              ]
            }
          }
        },
        "gridPos": {"h": 8, "w": 6, "x": 6, "y": 0}
      },
      {
        "id": 3,
        "title": "活跃告警数量",
        "type": "stat",
        "targets": [
          {
            "expr": "lifeverse_alerts_active",
            "legendFormat": "活跃告警"
          }
        ],
        "fieldConfig": {
          "defaults": {
            "color": {
              "mode": "thresholds"
            },
            "thresholds": {
              "steps": [
                {"color": "green", "value": 0},
                {"color": "yellow", "value": 5},
                {"color": "red", "value": 20}
              ]
            }
          }
        },
        "gridPos": {"h": 8, "w": 6, "x": 12, "y": 0}
      },
      {
        "id": 4,
        "title": "可用服务数量",
        "type": "stat",
        "targets": [
          {
            "expr": "lifeverse_services_available",
            "legendFormat": "可用服务"
          }
        ],
        "gridPos": {"h": 8, "w": 6, "x": 18, "y": 0}
      }
    ],
    "time": {
      "from": "now-1h",
      "to": "now"
    },
    "refresh": "30s"
  }
}
EOF

# 启动监控服务
echo "🐳 启动监控容器..."
docker-compose -f docker-compose.monitoring.yml up -d

# 等待服务启动
echo "⏳ 等待服务启动..."
sleep 30

# 检查服务状态
echo "🔍 检查服务状态..."

services=("prometheus:9090" "grafana:3000" "alertmanager:9093" "loki:3100")
for service in "${services[@]}"; do
    name=$(echo $service | cut -d: -f1)
    port=$(echo $service | cut -d: -f2)
    
    if curl -s -f "http://localhost:$port" > /dev/null; then
        echo "✅ $name 服务运行正常 (端口: $port)"
    else
        echo "❌ $name 服务启动失败 (端口: $port)"
    fi
done

echo ""
echo "🎉 监控系统启动完成！"
echo ""
echo "📊 访问地址："
echo "  - Prometheus: http://localhost:9090"
echo "  - Grafana: http://localhost:3000 (admin/lifeverse123)"
echo "  - AlertManager: http://localhost:9093"
echo "  - Jaeger: http://localhost:16686"
echo ""
echo "📝 使用说明："
echo "  1. 确保LifeVerse应用正在运行 (端口8080)"
echo "  2. 在Grafana中导入仪表盘配置"
echo "  3. 配置告警规则和通知渠道"
echo ""
echo "🛠️ 管理命令："
echo "  - 停止监控: docker-compose -f docker-compose.monitoring.yml down"
echo "  - 查看日志: docker-compose -f docker-compose.monitoring.yml logs -f"
echo "  - 重启服务: docker-compose -f docker-compose.monitoring.yml restart"